import { defineComponent, onErrorCaptured, ref, type VNode } from "vue";

type ErrorBoundaryProps = {
  fallback: (p: { error: unknown }) => VNode;
};

// TODO: 用 slot
export default defineComponent<ErrorBoundaryProps>({
  props: ["fallback"],
  setup(p: ErrorBoundaryProps, { slots }) {
    const error = ref<unknown>();

    onErrorCaptured((err) => {
      error.value = err;
      return false; // 防止错误冒泡
    });

    return () => <div>{error.value ? p.fallback({ error: error.value }) : slots.default?.()}</div>;
  },
});
